package com.ffs.lock;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 对象锁持有者，（对外暴露获取方式）
 *
 * @author ffs80 created 2021/7/2
 */
public class ObjectLockHolder {
    private static final ConcurrentHashMap<Class<?>, Holder> HOLDERS = new ConcurrentHashMap<>();

    public ObjectLock getLock(Object object) {
        Holder holder = getHolder(object.getClass());
        ObjectLock lock = holder.getLock(object);
        return lock;
    }

    private Holder getHolder(Class<?> clazz) {
        Holder holder = HOLDERS.get(clazz);
        if (holder != null) {
            return holder;
        }
        HOLDERS.putIfAbsent(clazz, new Holder(clazz));
        return HOLDERS.get(clazz);
    }

    public ReentrantLock getTieLock(Class<?> clazz) {
        Holder holder = getHolder(clazz);
        return holder.getTieLock();
    }

    public int count(Class<?> clazz) {
        if (HOLDERS.containsKey(clazz)) {
            Holder holder = getHolder(clazz);
            return holder.count();
        }
        return 0;
    }
}
